<?php
require_once dirname(__DIR__) . '/lib/utils.php';
/**
 * 采集大乐透历史开奖数据
 * 大乐透开奖时间：每周一、三、六 21:25 开奖
 * 官网：https://www.lottery.gov.cn/dlt/index.html
 * 定时任务：30 21 * * * dltcj.php
 * @version 1.0.0
 */
class SpiderModel
{
    protected $logFilename = '';

    public function __construct()
    {
        $this->logFilename = dirname(__DIR__) . '/data/log/spider-' . date('Ym') . '.log';
        if (!file_exists(dirname($this->logFilename))) {
            mkdir(dirname($this->logFilename), 0777, true);
        }
    }

    public function fetchDlt($isEcho = true)
    {
        savelog($this->logFilename, '【大乐透】采集开始', $isEcho);
        $url = 'https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=60&isVerify=1&pageNo=1&termLimits=60';

        $dataRoot = dirname(__DIR__) . '/data/dlt/';
        if (!file_exists($dataRoot)) {
            mkdir($dataRoot, 0777, true);
        }

        $messageArr = [];
        $cacheFile = $dataRoot . 'cache-' . date('Ymd') . '.json';

        // 保存一手的官方数据到缓存文件
        if (file_exists($cacheFile)) {
            $content = file_get_contents($cacheFile);
            $messageArr[] = '获取本地缓存数据';
            savelog($this->logFilename, '获取本地缓存数据', $isEcho);
        } else {
            $content = file_get_contents($url);
            if (strpos($content, 'GB2312') > -1) {
                $content = mb_convert_encoding($content, 'utf-8', 'GB2312');
            }
            file_put_contents($cacheFile, $content);
            $messageArr[] = '获取远程官方数据';
            savelog($this->logFilename, '获取远程官方数据', $isEcho);
        }

        if (!$content) {
            savelog($this->logFilename, '获取数据失败', $isEcho);
            return message(null, '获取数据失败', 500);
        }

        // 解析官方数据
        $list = json_decode($content, true)['value']['list'];
        $data = [];
        foreach ($list as $row) {
            $data[] = [
                'lotteryDrawNum' => trim($row['lotteryDrawNum']),
                'lotteryDrawTime' => trim($row['lotteryDrawTime']),
                'lotteryDrawResult' => trim($row['lotteryDrawResult']),
            ];
        }
        $messageArr[] = '采集 ' . count($data);
        savelog($this->logFilename, '采集 ' . count($data), $isEcho);

        $filename = $dataRoot . '/data-' . date('Ymd') . '.json';
        file_put_contents($filename, json_encode($data, JSON_UNESCAPED_UNICODE));

        // 合并增量数据
        $filename = $dataRoot . '/data-all.json';
        if (file_exists($filename)) {
            $list = json_decode(trim(file_get_contents($filename)), true);
            $lastIssue = $list[0]['lotteryDrawNum'];
            foreach ($data as $i => $row) {
                if ($row['lotteryDrawNum'] == $lastIssue) {
                    break;
                }
                array_splice($list, $i, 0, [$row]);
            }
            $data = $list;
            unset($list);
        }

        file_put_contents($filename, json_encode($data, JSON_UNESCAPED_UNICODE));

        $messageArr[] = '采集完成';
        savelog($this->logFilename, '【大乐透】采集完成', $isEcho);
        return message(null, '【大乐透】' . implode(' -- ', $messageArr));
    }
    /**
     * 采集双色球历史开奖数据
     * 双色球开奖时间：每周二、四、日 21：15 开奖
     * 官网：https://www.cwl.gov.cn/ygkj/kjgg/
     * 定时任务：30 21 * * * dltcj.php
     * @version 1.0.0
     */
    public function fetchSsq($isEcho = true)
    {
        savelog($this->logFilename, '【双色球】采集开始', $isEcho);
        // https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&pageNo=1&pageSize=60&systemType=PC
        $url = 'https://www.00038.cn/kjh/ssq/history.htm';

        $dataRoot = dirname(__DIR__) . '/data/ssq/';
        if (!file_exists($dataRoot)) {
            mkdir($dataRoot, 0777, true);
        }
        $messageArr = [];
        $cacheFile = $dataRoot . 'cache-' . date('Ymd') . '.html';

        if (file_exists($cacheFile)) {
            $content = file_get_contents($cacheFile);
            $messageArr[] = '获取本地缓存数据';
            savelog($this->logFilename, '获取本地缓存数据', $isEcho);
        } else {
            $content = file_get_contents($url);
            if (strpos($content, 'GB2312') > -1) {
                $content = mb_convert_encoding($content, 'utf-8', 'GB2312');
            }
            file_put_contents($cacheFile, $content);
            $messageArr[] = '获取远程官方数据';
            savelog($this->logFilename, '获取远程官方数据', $isEcho);
        }

        if (!$content) {
            savelog($this->logFilename, '获取数据失败', $isEcho);
            return message(null, '获取数据失败', 500);
        }

        // 解析tbody
        preg_match('/<table class="kjhTable">(.*?)<\/table>/is', $content, $match);
        if (!$match) {
            savelog($this->logFilename, '数据解析失败', $isEcho);
            return message(null, '数据解析失败', 500);
        }
        $match[1] = trim(preg_replace('/<thead>.*?<\/thead>/is', '', $match[1]));
        // 解析 tr
        preg_match_all('/<tr[^>]*>(.*?)<\/tr>/is', $match[1], $matches);
        // 解析 td
        $data = [];
        foreach ($matches[1] as $tr) {
            preg_match_all('/<td[^>]*>(.*?)<\/td>/is', $tr, $tds);
            $data[] = [
                'lotteryDrawNum' => trim(strip_tags($tds[1][0])),
                'lotteryDrawTime' => trim(strip_tags($tds[1][1])),
                'lotteryDrawResult' => trim(preg_replace('/\s+/is', ' ', str_replace('+', '', strip_tags($tds[1][2])))),
            ];
        }
        $messageArr[] = '采集数量 ' . count($data);
        savelog($this->logFilename, '采集数量 ' . count($data), $isEcho);

        $filename = $dataRoot . '/data-' . date('Ymd') . '.json';
        file_put_contents($filename, json_encode($data, JSON_UNESCAPED_UNICODE));

        // 合并数据
        $filename = $dataRoot . '/data-all.json';
        if (file_exists($filename)) {
            $list = json_decode(trim(file_get_contents($filename)), true);
            $lastIssue = $list[0]['lotteryDrawNum'];
            foreach ($data as $i => $row) {
                if ($row['lotteryDrawNum'] == $lastIssue) {
                    break;
                }
                array_splice($list, $i, 0, [$row]);
            }
            $data = $list;
            unset($list);
        }

        file_put_contents($filename, json_encode($data, JSON_UNESCAPED_UNICODE));

        $messageArr[] = '采集完成';
        savelog($this->logFilename, '【双色球】采集完成', $isEcho);
        return message(null, '【双色球】' . implode(' -- ', $messageArr));
    }
}